/**
 * @file ext-primitive-lib.js
 *
 * @license MIT
 *
 * @copyright 2010 Christian Tzurcanu, 2010 Alexis Deveria
 *
 */


const name = 'basic-shaps'
const defsIdMap = new Map();
const defsSymbolMap = new Map()


const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
  return translationModule
}
const ns = {
  svg: 'http://www.w3.org/2000/svg',
  xlink: 'http://www.w3.org/1999/xlink'
}

export default {
  name,
  async init() {
    const svgEditor = this
    const svgCanvas = svgEditor.svgCanvas
    const { $id, $click, $qq, $ } = svgCanvas
    const svgroot = svgCanvas.getSvgRoot()
    let lastBBox = {}
    const translationModule = await loadExtensionTranslation(svgEditor)

    var modeId = 'shaps'
    const startClientPos = {}

    let curShape, defs
    let startX
    let startY

    const getLastCharStart =(char,str,end=false)=>{
      try{
        const lastUnderscoreIndex = str.lastIndexOf(char);
        let result;
        if (lastUnderscoreIndex !== -1 && str.charAt(lastUnderscoreIndex + 1) !== char) {
          if(end){
            result = str.substr(lastUnderscoreIndex+1);
          }else{
            result = str.substr(0, lastUnderscoreIndex);
          }
          
        }
        return result;

      }catch(error){
        console.log("我进入错误",str)
      }
     
    }

    const addElement = (curShape, element, params) => {
      let children = $(element).children()
      Array.from(children).forEach((elem, i) => {
        let tagName = elem.tagName;
        if (tagName == 'g') {
          if (elem.classList.contains("layer")) {
            let title = $(elem).find("title")[0]
            var symbolId = params.shapTitle + "_" + title.textContent.trim().replace(" ", "")
            params.first_symbolId = symbolId;
            if (defsSymbolMap.get(symbolId) == null) {
              let childShape = svgCanvas.getDOMDocument().createElementNS(ns.svg, 'symbol')
              childShape.setAttribute("id", symbolId)
              childShape.setAttribute("del", params.first_symbolId)
              childShape.setAttribute("viewBox", params.viewBox)
              childShape.setAttribute("preserveAspectRatio", "xMidYMid meet")
             
              defsSymbolMap.set(symbolId, childShape)
              addElement(defsSymbolMap.get(symbolId), elem, params);
            }
            if (svgCanvas.findDuplicateGradient(defsSymbolMap.get(symbolId)) == null) {
              svgCanvas.findDefs().append(defsSymbolMap.get(symbolId))
            }
          }
          else {
            addElement(curShape, elem, params);
          }
        } else {
          if (tagName == 'title' || tagName == 'defs') {
            return
          }
          let newElement = $(elem).clone().attr({
            id: svgCanvas.getNextId(),
          });

          let fillAttr = $(elem).attr('fill')
          let strokeAttr = $(elem).attr('stroke')



          const fillAttrId = _.trimEnd(_.trimStart(fillAttr, 'url(#'), ')')
          const strokeAttrId = _.trimEnd(_.trimStart(strokeAttr, 'url(#'), ')')
        

          if (defsIdMap.has(fillAttrId)) {
            $(newElement).attr('fill', `url(#${defsIdMap.get(fillAttrId)})`)
          }

          if (defsIdMap.has(strokeAttrId)) {
            $(newElement).attr('stroke', `url(#${defsIdMap.get(strokeAttrId)})`)
          }

          $(curShape).append(newElement);
          // if (tagName == "path") {
          //   let path = newElement[0]
          //   const d = newElement.attr("d");
          //   if (/[a-z]/.test(d)) {
          //     const convertedPath = svgCanvas.pathActions.convertPath(path);
          //     path.setAttribute('d', convertedPath);
          //     svgCanvas.pathActions.fixEnd(path);
          //   }
          //   svgCanvas.recalculateDimensions(path);
          // }
        }
      });
    };

    const generateDefs = (shapTitle, dom) => {
      var viewBox = $(dom).attr("viewBox")
      var arra = viewBox.split(" ")
      viewBox = `${parseInt(arra[0]) - 5} ${parseInt(arra[1]) - 5}  1400 1100`
     

      var defs = $(dom).find("defs>*");
     

      var params = { viewBox: viewBox, first_symbolId: null, shapTitle: shapTitle }
      if (defs.length > 0) {
        Array.from(defs).forEach((elem, i) => {
          const oldId = elem.id;
          var def_ = svgCanvas.findDuplicateGradient(elem)
          if (def_ == null) {
            const newId = svgCanvas.getNextId()
            elem.setAttribute('id', newId)
            defsIdMap.set(oldId, newId)
            // console.log(elem,"原来没有我加入的元素")
            svgCanvas.findDefs().append(elem)
            
          } else {
            defsIdMap.set(oldId, def_.id)
          }
        })
      }

   

      addElement(null, dom, params)
    }

    return {
      callback() {
        if ($id('tool_shaps') === null) {
          var buts = translationModule.default.buttons[0]
          var index = 2;
          for (let key in buts) {
            let tool_id = `tool_${key}`
            const butTemplate = `
            <se-button id="${tool_id}" key=${key} title="${buts[key]}" src="${key.toLowerCase()}.svg">
            </se-button>`
            svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), butTemplate, index)
            $click($id(tool_id), (e) => {
              e.stopPropagation()
              e.preventDefault()
              // var _key = e.target.getAttribute('key')
              if (this.leftPanel.updateLeftPanel(tool_id)) {
                const elem = svgCanvas.getSelectedElements()
                if (elem.length == 1 && elem[0].getAttribute("doc-type") == key) {
                  // svgCanvas.setMode("changePic_" + key)
                  // window.changePic = true

                } else {
                  svgCanvas.setMode(key)
                }
                const $imgDialog = $id('se-graphiceditor')
                $imgDialog.setAttribute('dialog', 'open')
                $imgDialog.setAttribute('lib', key)
                modeId = key
              }
            })
            index++;
          }
        }

        $id('se-graphiceditor').addEventListener(
          'change',
          function (e) {
            if (e.detail.dialog === 'closed') {
              const $editDialog = $id('se-graphiceditor')
              $editDialog.setAttribute('dialog', 'close')
            }
          }.bind(this)
        )
      },
      mouseDown(opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) { return undefined }
        if (!window.dataShap || !window.docType) {
          return false;
        }
        var el = svgCanvas.getSvgContent()
        if (el.getAttribute("xmlns:xlink")) {
          el.setAttribute("xmlns:xlink", ns.xlink)
        }
        const curContent = window.dataShap;
        const curType = window.docType;
        const shapTitle = window.shapTitle;
        const curStyle = svgCanvas.getStyle()
        var width = parseInt($(curContent).attr("width"))
        var height = parseInt($(curContent).attr("height"))
        var viewBox = $(curContent).attr("viewBox")
        var arra = viewBox.split(" ")
        viewBox = `${parseInt(arra[0]) - 5} ${parseInt(arra[1]) - 5}  1400 1100`

        var params = { viewBox: viewBox, first_symbolId: null, shapTitle: shapTitle }

        defs = $(curContent).find("defs>*");

      

        if (defs.length > 0) {
          Array.from(defs).forEach((elem, i) => {
           
            const oldId = elem.id;
            var def_ = svgCanvas.findDuplicateGradient(elem)
            if (def_ == null) {
              const newId = svgCanvas.getNextId()
              elem.setAttribute('id', newId)
              defsIdMap.set(oldId, newId)
              svgCanvas.findDefs().append(elem)
              
            } else {
              defsIdMap.set(oldId, def_.id)
            }
          })
        }
        curShape = svgCanvas.addSVGElementsFromJson({
          element: 'g',
          attr: {
            id: svgCanvas.getNextId(),
            'doc-type': curType,
            opacity: curStyle.opacity,
            class: 'ems',
          }
        });
        addElement(curShape, curContent, params);
        var use = svgCanvas.addSVGElementsFromJson({
          element: 'use',
          attr: {
            opacity: curStyle.opacity,
            class: 'use',
            "xlink:href": `#${params.first_symbolId}`,
            x: 0, y: 0, width: width, height: height
          }
        });
        curShape.append(use)
        startX = opts.start_x
        var x = startX
        startY = opts.start_y
        var y = startY

        if (svgCanvas.getCurConfig().gridSnapping) {
          x = svgCanvas.snapToGrid(x)
          y = svgCanvas.snapToGrid(y)
        }

        startClientPos.x = opts.event.clientX
        startClientPos.y = opts.event.clientY

        curShape.setAttribute('transform', 'translate(' + x + ',' + y + ') scale(0.2) translate(' + -x + ',' + -y + ')')

        svgCanvas.recalculateDimensions(curShape)

        lastBBox = curShape.getBBox()

        return {
          started: true
        }
      },
      mouseMove(opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) { return }

        const zoom = svgCanvas.getZoom()
        const evt = opts.event

        var x = opts.mouse_x / zoom
        var y = opts.mouse_y / zoom

        if (svgCanvas.getCurConfig().gridSnapping) {
          x = svgCanvas.snapToGrid(x)
          y = svgCanvas.snapToGrid(y)
        }

        const tlist = curShape.transform.baseVal
        const box = curShape.getBBox()
        const left = box.x; const top = box.y

        const newbox = {
          x: Math.min(startX, x),
          y: Math.min(startY, y),
          width: Math.abs(x - startX),
          height: Math.abs(y - startY)
        }

        let sx = (newbox.width / lastBBox.width) || 1
        let sy = (newbox.height / lastBBox.height) || 1

        // Not perfect, but mostly works...
        let tx = 0
        if (x < startX) {
          tx = lastBBox.width
        }
        let ty = 0
        if (y < startY) {
          ty = lastBBox.height
        }

     

        // update the transform list with translate,scale,translate
        const translateOrigin = svgroot.createSVGTransform()
        const scale = svgroot.createSVGTransform()
        const translateBack = svgroot.createSVGTransform()

        translateOrigin.setTranslate(-(left + tx), -(top + ty))
        if (!evt.shiftKey) {
          const max = Math.min(Math.abs(sx), Math.abs(sy))

          sx = max * (sx < 0 ? -1 : 1)
          sy = max * (sy < 0 ? -1 : 1)
        }
        if (isFinite(sx) && isFinite(sy)) {
          scale.setScale(sx, sy)
        } else {
          // console.log(sx,sy,"我学生的积分了")
          scale.setScale(1,1)
        }
        translateBack.setTranslate(left + tx, top + ty)
        tlist.appendItem(translateBack)
        tlist.appendItem(scale)
        tlist.appendItem(translateOrigin)

        svgCanvas.recalculateDimensions(curShape)

        lastBBox = curShape.getBBox()
        return {
          started: true
        }
      },
      mouseUp(opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) { return undefined }
        return {
          keep: true,
          element: curShape,
        }
      },
      async reloadSymbol() {
        const allShapes = []
        defsSymbolMap.clear()
        defsIdMap.clear()
        // let chartName = window.localStorage.getItem("svg-edit-graphicType") +"/" +window.localStorage.getItem("svg-edit-graphicDesc")
        // const responseChart = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/graphics/file/${chartName}`)
        // const xmltext = await responseChart.json()
        // let svgString = decodeURIComponent(escape(atob(xmltext.data[0].content)))
        // let defs = $(svgString).children('defs').last();
        const defs = svgCanvas.getSvgContent().getElementsByTagNameNS(ns.svg, 'defs')
        if (!defs || !defs.length) {
          return 0
        }
        
        Array.prototype.forEach.call(defs, (def, i) => {
          const defelems = def.querySelectorAll(
            'symbol'
          )
          i = defelems.length
          while (i--) {
            const defelem = defelems[i]
            const del = defelem.getAttribute("del");
            if(del!==null){
              // console.log(del,defelem,"有del属性的")
              defelem.setAttribute("id",del)
            }
            const { id } = defelem
            if (del && del.indexOf("gzpai") == -1) {
              const lastChar = getLastCharStart("_", del)
              if (!allShapes.includes(lastChar)) {
                allShapes.push(lastChar)
              }
              svgCanvas.setRemovedElements(id, defelem);

              defelem.remove()
            }
          }
        })



       



        const response = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/primitive/list`)
        const data = (await response.json()).data;
        for (var key in data) {
          if (data[key].length > 0) {
            for (var i = 0; i < data[key].length; i++) {
              if (!allShapes.includes(data[key][i].title)) {
                continue
              }
              var reallyimgSrc = decodeURIComponent(escape(atob(data[key][i].content)))
              generateDefs(data[key][i].title, reallyimgSrc)
            }
          }
        }

        
        let DefsElement  =  $(svgCanvas.getSvgContent()).find("defs").last().children();
        let DefsType = new Map();
        
        for(let i=0;i<DefsElement.length;i++){
           let tagName = $(DefsElement[i]).prop("tagName");
           if(tagName=="symbol"){
            //  console.log(getLastCharStart("_",$(DefsElement[i]).attr("id")))
             if(!$(getLastCharStart("_",$(DefsElement[i]).attr("id")))){
              //  console.log($(DefsElement[i]),"相应元素")
             }
             if($(DefsElement[i]).attr("id")!=undefined){
              let type = getLastCharStart("_",$(DefsElement[i]).attr("id"));
              DefsType.set(type,$(DefsElement[i]).attr("id"))
             }
            
           }

          
        }

        console.log(DefsType,"我存的map")

        


         
        let emsObj = svgCanvas.getSvgContent().querySelectorAll(".ems");
        for(let i=0;i<emsObj.length;i++){
          let ems  = $(emsObj[i]);
          if(ems.attr("doc-type")=='barry' || ems.attr("doc-type")=='gzpai'){
            continue

          }

          let useidSplice  = $(ems).children("use").attr("xlink:href")
          if(useidSplice!="" && useidSplice!=undefined){
            let spliceKey  = getLastCharStart("_",useidSplice);
            if(DefsType.get(spliceKey.replace(/^#*/, ''))){
               $(ems).children("use").attr("xlink:href","#"+DefsType.get(spliceKey.replace(/^#*/, '')))
            }

          }
        
        }


        
      },
      updateDZ(data) {
        const elem = svgCanvas.getSelectedElements();
        var res = data.data;
        var idstring = `${res.tableValue}:${res.equipmentLable}:${res.domainID}`
        $(elem).attr("state", btoa(unescape(encodeURIComponent(JSON.stringify(data)))))
        $(elem).attr("data", idstring)
      },
      // changePic(opts) {
      //   const elem = svgCanvas.getSelectedElements();
      //   var docType = $(elem).attr("doc-type")
      //   if (docType) {
      //     var tool_id = "tool_" + docType
      //     const $imgDialog = $id('se-graphiceditor')
      //     $imgDialog.setAttribute('dialog', 'open')
      //     $imgDialog.setAttribute('lib', docType)
      //   }
      // },
      // samesizechange(opts) {
      //   if (!window.dataShap || !window.docType) {
      //     return false;
      //   }
      //   var el = svgCanvas.getSvgContent()
      //   if (el.getAttribute("xmlns:xlink")) {
      //     el.setAttribute("xmlns:xlink", ns.xlink)
      //   }
      //   const curContent = window.dataShap;
      //   const curType = window.docType;
      //   const shapTitle = window.shapTitle;
      //   const curStyle = svgCanvas.getStyle()

      //   var width = parseInt($(curContent).attr("width"))
      //   var height = parseInt($(curContent).attr("height"))
      //   var viewBox = $(curContent).attr("viewBox")
      //   var arra = viewBox.split(" ")
      //   viewBox = `${parseInt(arra[0]) - 5} ${parseInt(arra[1]) - 5}  1400 1100`

      //   var params = { viewBox: viewBox, first_symbolId: null, shapTitle: shapTitle }
        
      //   defs = $(curContent).find("defs>*")

      //   if (defs.length > 0) {
      //     Array.from(defs).forEach((elem, i) => {
      //       const oldId = elem.id

      //       var def_ = svgCanvas.findDuplicateGradient(elem)
      //       if (def_ == null) {
      //         const newId = svgCanvas.getNextId()
      //         elem.setAttribute('id', newId)
      //         defsIdMap.set(oldId, newId)
      //         svgCanvas.findDefs().append(elem)
      //       } else {
      //         defsIdMap.set(oldId, def_.id)
      //       }
      //     })
      //   }

      //   curShape = svgCanvas.getSelectedElements()[0]
      //   var bbox = $(curShape).find("use")[0].getBBox()
      //   addElement(curShape, curContent, params);
      //   $(curShape).find("use").attr("xlink:href", `#${params.first_symbolId}`)
      //   var usebox = $(curShape).find("use")[0].getBBox()
      //   const tlist = $(curShape).find("use")[0].transform.baseVal

      //   const translateOrigin = svgroot.createSVGTransform()
      //   const scale = svgroot.createSVGTransform()
      //   const translateBack = svgroot.createSVGTransform()

      //   translateOrigin.setTranslate(-(bbox.x), -(bbox.y))
      //   translateBack.setTranslate((bbox.x), (bbox.y))
      //   scale.setScale(bbox.width / usebox.width, bbox.height / usebox.height)
      //   tlist.appendItem(translateBack)
      //   tlist.appendItem(scale)
      //   tlist.appendItem(translateOrigin)
      //   svgCanvas.recalculateDimensions(curShape)
      //   svgCanvas.setMode(curType)
      // }
    }
  }
}
